package com.ruibang.glass.equipment.service.impl.device;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.jdbc.StringUtils;
import com.ruibang.glass.equipment.constant.EquipmentErrorCode;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.entity.device.InstrumentRegister;
import com.ruibang.glass.equipment.entity.device.ScrapReport;
import com.ruibang.glass.equipment.mapper.device.ScrapReportMapper;
import com.ruibang.glass.equipment.service.InstrumentRegisterService;
import com.ruibang.glass.equipment.service.ScrapReportService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ScrapReportServiceImpl extends ServiceImpl<ScrapReportMapper, ScrapReport> implements ScrapReportService {
    @Autowired
    private InstrumentRegisterService instrumentRegisterService;

    /**
     * 报废报表列表
     * @param deviceAllPageReq
     * @return
     */

    @Override
    public IPage<ScrapReport> getBoilerList(DeviceAllPageReq deviceAllPageReq) {
        return baseMapper.getCheckList(new Page(deviceAllPageReq.getPageNo(), deviceAllPageReq.getPageSize()), deviceAllPageReq);
    }

    /**
     * 新增修改
     * @param accidentRegister
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody updateOrAddById(ScrapReport accidentRegister) {
        if (StringUtils.isNullOrEmpty(accidentRegister.getId())) {
            baseMapper.insert(accidentRegister);
            return ResultBody.success();
        }
        baseMapper.updateById(accidentRegister);
        return ResultBody.success();
    }

    /**
     * 新增
     * @param accidentRegister
     */
    @Override
    public void insertById(ScrapReport accidentRegister) {
        if (CollectionUtils.isNotEmpty(accidentRegister.getIds())) {
            List<ScrapReport> list = new ArrayList<>();
            List<InstrumentRegister> instrumentRegisters = instrumentRegisterService.listByIds(accidentRegister.getIds());
            for (InstrumentRegister instrumentRegister : instrumentRegisters) {
                ScrapReport scrapReport = new ScrapReport();
                scrapReport.setEquipmentNumber(instrumentRegister.getNumber());
                scrapReport.setEquipmentName(instrumentRegister.getName());
                scrapReport.setInstrumentId(instrumentRegister.getId());
                list.add(scrapReport);
            }
            baseMapper.insertBatch(list);
        }
        if (org.apache.commons.lang.StringUtils.isNotBlank(accidentRegister.getId())) {
            InstrumentRegister instrumentRegister = instrumentRegisterService.getById(accidentRegister.getId());
            ScrapReport scrapReport = new ScrapReport();
            scrapReport.setEquipmentNumber(instrumentRegister.getNumber());
            scrapReport.setEquipmentName(instrumentRegister.getName());
            scrapReport.setInstrumentId(instrumentRegister.getId());
            baseMapper.insert(scrapReport);
        }

    }

    /**
     * 导出
     * @param machiningReq
     * @param response
     */
    @Override
    public void export(DeviceAllPageReq machiningReq, HttpServletResponse response) {
        String fileName = "报废报表" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ".xlsx";
        try {
            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            // 设置响应内容类型和字符编码
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");

            // 设置Content-Disposition头部，告诉浏览器这是一个文件下载请求
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

            // 获取导出数据
            IPage<ScrapReport> checkList = baseMapper.getCheckList(new Page<ScrapReport>(0L, 2000L), machiningReq);
            List<ScrapReport> list = checkList.getRecords();

            // 使用EasyExcel写入数据到响应输出流
            EasyExcel.write(response.getOutputStream(), ScrapReport.class).excelType(ExcelTypeEnum.XLSX).sheet("报废报表").doWrite(list);

            // 刷新输出流
            response.flushBuffer();
        } catch (IOException e) {
            // 处理异常，例如设置错误状态码或错误消息
            throw new ServiceException(EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getCode(), EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getMsg());
        }
    }


}
